/**
 * @description:
 * @Author HP
 * @create 2022/6/23 14:37
 */

import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import com.tzy.rpc.loadbalancer.RoundRobinLoadBalancer;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author HP
 * @create 2022-06-23 14:37
 * @desc
 **/
public class RedisWithLua {
    Jedis jedis=new Jedis("localhost",6379);

    @Test
    public void test1(){
        System.out.println(jedis.ping());
        jedis.set("name", "456");
        System.out.println(jedis.get("name"));
    }

    @Test
    public void test0() throws IOException {
        InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("luaScript/luaTest1.lua"));
        String script = CharStreams.toString(reader);
        System.out.println(script);
        jedis.eval(script, Lists.newArrayList("lua"),Lists.newArrayList("789"));
    }

    @Test
    public void test2() throws IOException {
        InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("luaScript/luaTest2.lua"));
        String script = CharStreams.toString(reader);
        System.out.println(script);
        System.out.println(jedis.eval(script, Lists.newArrayList("lua","name"),Lists.newArrayList("")));
    }

    @Test
    public void test3(){
        System.out.println(jedis.setnx("name2", "456"));
        System.out.println(jedis.setnx("name1", "456"));
        System.out.println(jedis.setnx("name1", "789"));
    }

    @Test
    public void test4() throws IOException, InterruptedException {
        String serviceName="com.tzy.rpc.api.HelloService";
        int size=3;
        InputStreamReader reader = new InputStreamReader(RoundRobinLoadBalancer.class.getResourceAsStream("/luaScript/lockAndRelease.lua"));
        String script = CharStreams.toString(reader);
        for (int i = 0; i < 100; i++) {
            int index= ((Long)jedis.eval(script, Lists.newArrayList(serviceName+":idx",serviceName+":cnt",serviceName+":lock"), Lists.newArrayList(size+"", UUID.randomUUID()+""))).intValue();
            System.out.println(index);
            TimeUnit.MILLISECONDS.sleep(8);
        }
    }
}
